package com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.zhinenghuacangku_zhijian.R;
import com.xiaoxing.zhinenghuacangku_zhijian.R2;
import com.xiaoxing.zhinenghuacangku_zhijian.di.component.DaggerQuYangLieBiaoComponent;
import com.xiaoxing.zhinenghuacangku_zhijian.di.module.QuYangLieBiaoModule;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.contract.QuYangLieBiaoContract;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.presenter.QuYangLieBiaoPresenter;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.adapter.QuYangLieBiaoAdapter;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.entity.GetSimpleZoneBuffer;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.entity.QuYangLieBiao;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.NiceSpinner;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.ButtonUtils;

import static android.support.v7.widget.DividerItemDecoration.VERTICAL;
import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @ProjectName: a
 * @ackage: com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.activity
 * @ClassName: QuYangLieBiaoActivity
 * @Description: 取样列表  1、获取取样列表 2、发送抽样出库命令
 * @Author: 小星
 * @CreateDate: 2020/9/3 0003 20:32
 * @UpdateUser: 更新者：
 * @UpdateDate: 2020/9/3 0003 20:32
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
@Route(path = RouterHub.ZHI_NENG_HUA_CANG_KU_ZHI_JIAN_ACTIVITY_QU_YANG_LIE_BIAO)
public class QuYangLieBiaoActivity extends BaseActivity<QuYangLieBiaoPresenter> implements QuYangLieBiaoContract.View, QuYangLieBiaoAdapter.ChuKuInterface, OnRefreshListener {


    @BindView(R2.id.empty_text)
    TextView empty_text;
    @BindView(R2.id.empty_image)
    ImageView empty_image;
    @BindView(R2.id.empty)
    View mEmptyLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    private QuYangLieBiaoAdapter mAdapter;
    private List<QuYangLieBiao> mDataBeanList = new ArrayList<>();
    private List<QuYangLieBiao> groups = new ArrayList<QuYangLieBiao>();// 组元素数据列表
    private Map<String, List<QuYangLieBiao.MitemBean>> children = new HashMap<String, List<QuYangLieBiao.MitemBean>>();// 子元素数据列表
    private Map<Integer, Integer> mGroupsPosition = new HashMap<>();
    private AlertDialog mAlertDialog;
    private String mSelectedBufferId;
    private String mSelectedBufferName;
    private Disposable disposable;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerQuYangLieBiaoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .quYangLieBiaoModule(new QuYangLieBiaoModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_qu_yang_lie_biao; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.zhi_neng_cang_ku_zhi_jian_activity_qu_yang_lie_biao));
        initRefreshLayout();
        initRecyclerView();
        initEmpty();
        getQuYangLieBiao();
        startTimer();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new QuYangLieBiaoAdapter(this, groups, children, mGroupsPosition));
        //优化嵌套卡顿
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setItemViewCacheSize(600);
        RecyclerView.RecycledViewPool recycledViewPool = new RecyclerView.RecycledViewPool();
        mRecyclerView.setRecycledViewPool(recycledViewPool);
        mAdapter.setChuKuInterface(this);

    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    /**
     * @param
     * @return
     * @method
     * @description 获取质检列表
     * @date: 2020/9/3 0003 14:06
     * @author: 小星
     */
    private void getQuYangLieBiao() {
        clearData();

        showLoading();

        String methodNames = "SimpleOutStoreListForQuality";
        SoapParams paramss = null;
        paramss = new SoapParams();
        paramss.put("simpleGetterUserId", mSharedPreferencesHelper.getString(BaseConstants.UID));
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                        List<QuYangLieBiao> outOfTheLibraryLists = ArmsUtils.parseString2List(result, QuYangLieBiao.class);
                        mGroupsPosition.clear();
                        children.clear();
                        groups.clear();
                        mAdapter.setDataItems(getSampleItems(outOfTheLibraryLists));
                        mAdapter.notifyDataSetChanged();
                        mAdapter.expandAll();
                        mEmptyLayout.setVisibility(View.GONE);
                        mRecyclerView.setVisibility(View.VISIBLE);
                    } else {
                        clearData();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * 开始定时执行
     */
    private void startTimer() {
        stopTimer();
        disposable = Observable.interval(60, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Long aLong) throws Exception {
                        // 逻辑代码
                        getQuYangLieBiao();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    public void clearData() {
        mGroupsPosition.clear();
        children.clear();
        groups.clear();
        mEmptyLayout.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    public List<QuYangLieBiaoAdapter.OrderListItem> getSampleItems(List<QuYangLieBiao> quYangLieBiaos) {
        List<QuYangLieBiaoAdapter.OrderListItem> items = new ArrayList<>();

        for (int i = 0; i < quYangLieBiaos.size(); i++) {

            int groupPosition = items.size();
            mGroupsPosition.put(groupPosition, i);

            QuYangLieBiao quYangLieBiao = quYangLieBiaos.get(i);

            groups.add(quYangLieBiao);
            items.add(new QuYangLieBiaoAdapter.OrderListItem(quYangLieBiao));

            List<QuYangLieBiao.MitemBean> outList = quYangLieBiao.getMitem();

            List<QuYangLieBiao.MitemBean> products = new ArrayList<QuYangLieBiao.MitemBean>();


            for (int i1 = 0; i1 < outList.size(); i1++) {

                QuYangLieBiao.MitemBean outListBean = outList.get(i1);


                products.add(outListBean);

                items.add(new QuYangLieBiaoAdapter.OrderListItem(groupPosition, outListBean, i1, quYangLieBiao));
            }

            children.put(String.valueOf(groupPosition), products);// 将组元素的一个唯一值，这里取Id，作为子元素List的Key

        }
//        items.add(new OutOfTheLibraryAdapter.OrderListItem("", "", "", ""));

        return items;
    }

    /**
     * 停止定时执行
     */
    protected void stopTimer() {
        if (null != disposable) {
            disposable.dispose();
            disposable = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    @Override
    public void getQuYangLieBiaoDataSuccess(QuYangLieBiao entityData) {


    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

    }

    /**
     * @param
     * @return
     * @method
     * @description 点击出库按钮执行的方法：1、 先查询取样区 2、返回数据，弹出选择取样区的弹出框 3、选择取样区，点击取样
     * @date: 2020/9/3 0003 16:47
     * @author: 小星
     */
    @Override
    public void chuKu(QuYangLieBiao quYangLieBiao) {
        getSimpleZoneBuffer(quYangLieBiao);
    }

    /**
     * @param
     * @return
     * @method
     * @description 查询取样区列表
     * @date: 2020/9/3 0003 16:22
     * @author: 小星
     */
    private void getSimpleZoneBuffer(QuYangLieBiao quYangLieBiao) {
        showLoading();

        String methodNames = "GetSimpleZoneBuffer";
        SoapParams paramss = null;
        paramss = new SoapParams();
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                        showQuYangQu(result, quYangLieBiao);


                    } else {
                        clearData();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * @param
     * @return
     * @method
     * @description 弹出取样区
     * @date: 2020/9/3 0003 16:46
     * @author: 小星
     */
    private void showQuYangQu(String result, QuYangLieBiao quYangLieBiao) {


        View myView = LayoutInflater.from(this).inflate(R.layout.zhi_neng_cang_ku_zhi_jian_layout_qu_yang_qu, null);
        NiceSpinner niceSpinner = myView.findViewById(R.id.nice_position);
        List<GetSimpleZoneBuffer> getSimpleZoneBuffers = new Gson().fromJson(result, new TypeToken<List<GetSimpleZoneBuffer>>() {
        }.getType());

        if (getSimpleZoneBuffers != null && getSimpleZoneBuffers.size() > 0) {
            initSpPosition(getSimpleZoneBuffers, niceSpinner);
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setPositiveButton("取样", null);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        mAlertDialog = builder.create();
        mAlertDialog.setTitle("选择取样区");
        mAlertDialog.setView(myView);
        mAlertDialog.show();


        //拿到按钮并判断是否是POSITIVEBUTTON，然后我们自己实现监听
        mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ButtonUtils.isFastDoubleClick()) {

                    List<QuYangLieBiao.MitemBean> mitemBeanList = quYangLieBiao.getMitem();
                    int random = new Random().nextInt(mitemBeanList.size());
                    QuYangLieBiao.MitemBean mitemBean = mitemBeanList.get(random);
//                    if (mitemBean.getIsauto().equals("1")) {
//                        simpleOutStoreForQuality(quYangLieBiao, mitemBean);
//                    } else if (mitemBean.getIsauto().equals("0")) {
//                        peopleSendToSimpleOrder(quYangLieBiao, mitemBean);
//                    }
                    sendSimpleOrderToCGY(quYangLieBiao, mitemBean);
                    mAlertDialog.dismiss();
                } else {
                    showMessage("10s内请勿重复点击");
                }

            }
        });


    }

    private void initSpPosition(List<GetSimpleZoneBuffer> getSimpleZoneBuffers, NiceSpinner spPosition) {
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < getSimpleZoneBuffers.size(); i++) {
            list.add(String.valueOf(
                    new StringBuilder()
                            .append(getSimpleZoneBuffers.get(i).getBuffer_name())
            ));
        }
        mSelectedBufferId = getSimpleZoneBuffers.get(0).getId();
        mSelectedBufferName = getSimpleZoneBuffers.get(0).getBuffer_name();
        spPosition.attachDataSource(list);
        spPosition.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSelectedBufferId = getSimpleZoneBuffers.get(position).getId();
                mSelectedBufferName = getSimpleZoneBuffers.get(position).getBuffer_name();
            }
        });
    }

    /**
     * @param
     * @return
     * @method
     * @description 显示"取样"按钮,点击调用
     * @date: 2020/9/4 0004 10:51
     * @author: 小星
     */
    private void sendSimpleOrderToCGY(QuYangLieBiao quYangLieBiao, QuYangLieBiao.MitemBean mitemBean) {

        showLoading();
        String methodNames = "SendSimpleOrderToCGY";
        SoapParams paramss = null;
        paramss = new SoapParams();
        paramss.put("mid", mitemBean.getMid());
        paramss.put("spname", mitemBean.getSpname());
        paramss.put("spid", mitemBean.getSpid());
        paramss.put("bufferid", mSelectedBufferId);
        paramss.put("buffer_name", mSelectedBufferName);
        paramss.put("monthid", quYangLieBiao.getMonthid());
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                        showMessage("取样命令发送成功");
                        //命令发送成功，重新查询取样列表
                        getQuYangLieBiao();
                    } else {
                        showMessage("取样命令发送失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

}
